package com.itheima.service.Impl;

import com.itheima.exception.DeptException;
import com.itheima.mapper.DeptMapper;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    public List<Dept> findAll() {
        List<Dept> deptList = deptMapper.findAll();
        return deptList;
    }

    /**
     *注意：在页面原型中，要求如果该部门下关联的有员工，是不允许删除的，并提示错误信息：
     * "对不起，当前部门下有员工，不能直接删除"。(提示：可以通过自定义异常+全局异常处理器实现)
     * @param id
     */
    public void deleteById(Integer id) {
        Integer count = deptMapper.getEmpCountByDeptId(id);//查询该部门下有多少员工
        if (count > 0) {
            throw new DeptException("对不起，当前部门下有员工，不能直接删除！");
        }
        deptMapper.deleteById(id);
    }

    @Override
    public void addDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.addDept(dept);
    }

    @Override
    public Dept findById(Integer id) {
        return deptMapper.findById(id);
    }

    @Override
    public void updateDept(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }
}
